<template>
  <!-- 用于按钮和输入框的转换 -->
  <!-- 没实现先搁着，要用自定义组件的v-model -->
  <span>
    <el-button v-if="!isEdit" @click="showEdit()">
      <slot>点我输入</slot>
    </el-button>
    <el-input v-if="isEdit" v-model.trim="main" @blur="isEdit = false" @keyup.enter="isEdit = false" ref="editDom"
      :placeholder="placeholder" />
  </span>
</template>

<script>

import { computed, watch, nextTick } from 'vue'

export default {
  setup(props) {
    const isEdit = ref(false)
    const editDom = ref(null)

    // 显示对应的编辑器
    const showEdit = (isFocus) => {
      isEdit.value = true
      nextTick(() => {
        editDom.value.focus()
      })
    }

    // 编辑模式改变时要干的事
    watch(isEdit, (newValue) => {
      if (!newValue) {// 当推出编辑时
        console.log(props.data)

      }
    })

    let main = computed({
      get() {
        if (!props.index) return props.data
        return eval('props.data.' + props.index)
      },
      set(value) {
        console.log(props.data)
        console.log(value)
        if (!props.index) {
          props.data = value
          return;
        }
        // 仅用于字符串数据
        eval('props.data.' + props.index + '="' + value.toString() + '"')
      }
    })

    return {
      main, isEdit, editDom, showEdit
    };
  },
  // data:Proxy:响应对象，index:String：对象里面的数据项
  // placeholder:String input为空的提示信息
  // textPlaceholder: 数据项为空的时候，span中显示的东西
  props: ['data', 'index', 'placeholder', 'textPlaceholder']
};
</script>

<style scoped></style>